package com.tarena.lbs.activity.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.activity.dao.repository.ActivityRepository;
import com.tarena.lbs.activity.pojo.param.ActivityAddParam;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.activity.pojo.query.ActivityQuery;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.activity.service.ActivityService;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.coupon.api.CouponApi;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityRepository activityRepository;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private AttachApi attachApi;
    @DubboReference
    private CouponApi couponApi;

    /*
    * 活动详情
    * */
    @Override
    public ActivityVO activityDetail(Integer id) {
        log.info("查询活动详情入参:{}",id);
        // 添加参数校验
        if (id == null || id <= 0) {
            log.warn("查询活动详情参数无效: id={}", id);
            return null;
        }
        
        try {
            ActivityPO activityPO=activityRepository.getActivityById(id);
            ActivityVO activityVO=null;
            if (activityPO!=null){
                activityVO=new ActivityVO();
                BeanUtils.copyProperties(activityPO,activityVO);
                // 处理图片回显
                if (activityPO.getImgIds() != null && !activityPO.getImgIds().isEmpty()) {
                    List<String> imgPics = new ArrayList<>();
                    String[] imgIdArray = activityPO.getImgIds().split(",");
                    for (String imgId : imgIdArray) {
                        if (imgId != null && !imgId.trim().isEmpty()) {
                            try {
                                String imgUrl = attachApi.getAttachUrl(imgId.trim());
                                if (imgUrl != null) {
                                    imgPics.add(imgUrl);
                                }
                            } catch (Exception e) {
                                log.warn("获取图片URL失败，图片ID: {}", imgId, e);
                            }
                        }
                    }
                    activityVO.setImgPics(imgPics);
                }
            }
            log.info("查询活动详情成功，出参:{}",activityVO);
            return activityVO;
        } catch (Exception e) {
            log.error("查询活动详情异常，id={}", id, e);
            return null;
        }
    }

    /*
    * 活动查询列表
    * */
    @Override
    public PageResult<ActivityVO> pageList(ActivityQuery query) {
        log.info("查询活动列表入参:{}",query);
        AdminDto adminById = userApi.getAdminById(AuthenticationContextUtils.get().getId());
        if (adminById==null){
            throw new RuntimeException("商家不存在");
        }
        query.setBusinessId(adminById.getBusinessId());
        log.info("查询活动列表入参(检查business_id):{}",query);
        PageResult<ActivityVO> voPage = new PageResult<>();
        PageInfo<ActivityPO> pageInfo=activityRepository.pageList(query);
        voPage.setPageNo(pageInfo.getPageNum());
        voPage.setPageSize(pageInfo.getPageSize());
        voPage.setTotal(pageInfo.getTotal());
        List<ActivityVO> vos = null;
        List<ActivityPO> pos = pageInfo.getList();
        if (CollectionUtils.isNotEmpty(pos)){
            vos=pos.stream().map(po->{
                ActivityVO vo = new ActivityVO();//TOOD,活动奖励有问题待解决
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPage.setObjects(vos);
        return voPage;
    }

    /*
     *修改活动状态
     * */
    @Override
    public void updateStatus(Map<String, Integer> param) {
        log.info("修改活动状态入参:{}",param);
        activityRepository.updateStatus(param.get("id"),param.get("status"));
    }

    /*
    * 删除活动
    * */
    @Override
    public void delete(Integer id) {
        log.info("删除活动入参:{}",id);
        activityRepository.delete(id);
    }

    /*
    * 新增编辑活动
    * */
    @Override
    public void updateActivity(ActivityAddParam param) {
        log.info("新增编辑活动入参:{}",param);
        //对齐日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(false);
        Date startDate = null;
        Date endDate= null;
        try {
            startDate = sdf.parse(param.getStartDate());
            endDate = sdf.parse(param.getEndDate());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        ActivityPO activityPO=new ActivityPO();
        //获取商家id
        AdminDto adminDto=userApi.getAdminById(AuthenticationContextUtils.get().getId());
        param.setBusinessId(adminDto.getBusinessId());
        BeanUtils.copyProperties(param,activityPO);
        activityPO.setStartDate(startDate);
        activityPO.setEndDate(endDate);
        activityPO.setUpdateAt(new Date());
        log.info("新增编辑活动PO:{}",activityPO);
        if (param.getId()==null){
            //新增
            activityPO.setCreateAt(new Date());
            int status=getActivityStatus(startDate,endDate);
            activityPO.setStatus(status);
            activityPO.setRewardType(1);
            activityPO.setEnableStatus(1);
            activityPO.setChannelType(1);
            log.info("新增活动数据层入参:{}",activityPO);
            activityRepository.saveActivity(activityPO);
        }else {
            //编辑
            activityRepository.updateActivity(activityPO);
        }
    }

   /*
   * 每五分钟更新一次状态
   * */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void updateActivityStatus() {
        log.info("间隔定时任务开始执行：更新活动状态");
        Date now = new Date();
        List<ActivityPO> needCheckActivities = activityRepository.findNeedStatusUpdateActivities(
                DateUtils.addMinutes(now, 5),  // 5分钟后
                now                            // 当前时间
        );
        if (CollectionUtils.isEmpty(needCheckActivities)) {
            log.info("暂时没有需要更新状态的活动");
            return;
        }
        for (ActivityPO activity : needCheckActivities) {
            int newStatus = getActivityStatus(activity.getStartDate(), activity.getEndDate());
            if (activity.getStatus() != newStatus) {}
        }
    }

    private int getActivityStatus(Date startDate, Date endDate) {
        LocalDateTime currentDateTime = LocalDateTime.now();
        String formattedCurrentTime=currentDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.info("当前时间:{}",formattedCurrentTime);
        LocalDateTime startDateTime=startDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        LocalDateTime endDateTime=endDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        if (currentDateTime.isBefore(startDateTime)) {
            return 0; // 在开始时间之前
        } else if (currentDateTime.isAfter(endDateTime)) {
            return 2; // 在结束时间之后
        } else {
            return 1; // 在时间范围内（包括等于开始时间或结束时间）
        }
    }


}



















